<template>
  <div class="app-container projectList">
    <!-- 查询条件 -->
    <avue-form v-model="queryForm" :option="queryFormOption">
      <!--   客户名称   -->
      <!-- <template #cusId>
        <el-select
          v-model="queryForm.cusId"
          placeholder="请输入客户名称"
          class="w-full"
          clearable
          filterable
          suffix-icon="Search"
          remote-show-suffix
          :suffix-transition="false"
          remote
          :loading="loadingSelect"
          :loading-text="'加载中...'"
          :remote-method="queryCustomer"
        >
          <el-option
            v-for="item in parentOptions"
            :key="item.id"
            :label="item.customerName"
            :value="item.id"
          >
            <div>
              <span>{{ item.customerName }}</span>
              <span v-if="item.mainContactName"
                >({{ item.mainContactName }})</span
              >
              <span v-else>{{ item.mainContactName }}</span>
            </div>
          </el-option>
        </el-select>
      </template> -->
      <template #menu-form>
        <el-button icon="Search" type="primary" @click="handleSubmit"
          >查询</el-button
        >
        <el-button icon="RefreshLeft" @click="handleEmpty">重置</el-button>
        <el-button icon="Filter" link type="primary" @click="openDrawer"
          >高级筛选</el-button
        >
      </template>
    </avue-form>
    <!-- 操作按钮 -->
    <div>
      <el-button icon="Plus" type="primary" @click="handleAdd"
        >新建项目</el-button
      >
      <el-button
        :disabled="singleBtn"
        icon="EditPen"
        plain
        type="primary"
        @click="handleEdit"
        >编辑项目</el-button
      >
      <el-button
        :disabled="multipleBtn"
        icon="Delete"
        plain
        type="primary"
        @click="handleDel"
        >删除</el-button
      >
    </div>
    <!-- table 表格 -->
    <el-table
      ref="tableRef"
      v-loading="tableLoading"
      :data="tableData"
      border
      class="mt-20px"
      stripe
      style="width: 100%"
      @selection-change="handleTableSelect"
      @row-dblclick="handleClickProject"
    >
      <el-table-column align="center" type="selection" width="40" />
      <el-table-column align="left" label="项目编号" prop="proNum" width="230">
        <!-- <template #default="scope">
          <div
            class="cursor-pointer"
            style="color: #1890ff"
            @click="handleClickProject(scope.row)"
          >
            {{ scope.row.proNum }}
          </div>
        </template> -->
      </el-table-column>
      <el-table-column label="项目名称" prop="proName">
        <template #default="scope">
          <!-- @click="handleClickProject(scope.row)" cursor-pointer  -->
          <div class="truncate">
            <el-tooltip
              :content="scope.row.proName"
              class="box-item"
              effect="dark"
              placement="top-start"
            >
              {{ scope.row.proName }}
              <!-- {{
                scope.row.proName && scope.row.proName.length > 20
                  ? scope.row.proName.substr(0, 30) + '...'
                  : scope.row.proName
              }} -->
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="归属单位"
        prop="companyName"
        width="90"
      />
      <el-table-column key="proType" align="center" label="项目属性" width="90">
        <template #default="scope">
          <dict-tag :options="project_properties" :value="scope.row.proType" />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="项目负责人"
        prop="principal"
        width="100"
      />
      <el-table-column align="center" label="项目状态" width="130">
        <template #default="scope">
          <div>
            <dict-drop
              :options="project_phase"
              :value="scope.row.proSchedule"
            />
            <span v-if="scope.row.bpmnStatus" class="text-12px text-#999999"
              >（{{ scope.row.bpmnStatus }}）</span
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="投标结果" width="130">
        <template #default="scope">
          <div>
            <dict-drop
              :isDrop="false"
              :options="[
                {
                  label: '中标',
                  value: '1'
                },
                {
                  label: '未中标',
                  value: '0'
                }
              ]"
              :value="scope.row.biddingResult"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" prop="customer" width="280" />
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="tableTotal > 0"
      v-model:limit="queryForm.pageSize"
      v-model:page="queryForm.pageNum"
      :total="tableTotal"
      @pagination="getList"
    />
    <!-- 高级筛选 -->
    <advancedSearch
      :advancedSearchParam="advancedSearchParam"
      @closeAdvancedSearch="closeAdvancedSearchFn"
    >
      <div style="margin: -20px">
        <avue-form v-model="queryForm" :option="searchFormOption">
          <!--   客户名称   -->
          <template #cusId>
            <el-select
              v-model="queryForm.cusId"
              :loading="loadingSelect"
              :loading-text="'加载中...'"
              :remote-method="queryCustomer"
              :suffix-transition="false"
              class="w-full"
              clearable
              filterable
              placeholder="请输入客户名称"
              remote
              remote-show-suffix
              suffix-icon="Search"
            >
              <el-option
                v-for="item in parentOptions"
                :key="item.id"
                :label="item.customerName"
                :value="item.id"
              >
                <div>
                  <span>{{ item.customerName }}</span>
                  <span v-if="item.mainContactName"
                    >({{ item.mainContactName }})</span
                  >
                  <span v-else>{{ item.mainContactName }}</span>
                </div>
              </el-option>
            </el-select>
          </template>
        </avue-form>
        <el-row class="justify-center mt-30px">
          <el-button type="primary" @click="handleSubmit"
            ><el-icon><Search /></el-icon>查询</el-button
          >
          <el-button @click="handleEmpty"
            ><el-icon><RefreshLeft /></el-icon>重置</el-button
          >
        </el-row>
      </div>
    </advancedSearch>
    <!-- 弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @close="closeFn"
      @ok="selectDialogData"
    ></SelectDialog>
    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
      @ok="selectDialogData"
    ></SelectCustomer>
  </div>
</template>
<script name="ProjectList" setup>
import advancedSearch from './module/advancedSearch'
import {
  project_phase,
  business_attribute,
  project_properties,
  project_amount,
  parentOptions,
  queryCustomer,
  loadingSelect
} from '@/hooks/dict/useProject'
import { companyOption } from '@/hooks/dict/order'
import { useRouter } from 'vue-router'
import { getOrdproject, delProRemoveById } from '@/api/projectManage/project'
import { getPricipalId } from '@/utils/commo'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
const commonStore = useCommonStore()
const userStore = useUserStore()
// 通用数据store
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const principalIdsOption = ref([]) //项目负责人
const dialogParamA = ref({})
// 设置参数
const data = reactive({
  dialogParam: {}, //弹出框下拉框 设置传递的参数变量
  //高级筛选 弹出框
  advancedSearchParam: {
    drawerVisible: false
  },
  tableLoading: false, //
  queryForm: {
    principalId: [],
    cusId: null,
    pageNum: 1,
    pageSize: 10
  },
  // 查询条件form表单配置
  queryFormOption: {
    labelWidth: 10,
    menuSpan: 6,
    submitBtn: false,
    emptyBtn: false,
    column: [
      {
        prop: 'proName',
        placeholder: '请输入项目编号或项目名称',
        type: 'input',
        maxlength: 50,
        span: 4
      },
      {
        prop: 'proSchedule',
        placeholder: '请选择项目阶段',
        type: 'select',
        span: 3,
        dicData: project_phase
      },
      {
        prop: 'proType',
        placeholder: '请选择项目属性',
        type: 'select',
        span: 3,
        dicData: project_properties
      },
      {
        prop: 'principalId',
        placeholder: '请选择项目负责人',
        type: 'select',
        multiple: true,
        span: 4,
        props: {
          value: 'uuid'
        },
        clearable: false,
        dicData: principalIdsOption,
        click: ({ value, column }) => {
          // 3. 传递数据（下面字段都是必传）
          dialogParam.value.type = 'principalId'
          dialogParam.value.title = '请选择项目负责人'
          dialogParam.value.isDialog = true
          dialogParam.value.multiple = true
          dialogParam.value.nodeKey = 'uuid'
          dialogParam.value.defaultCheckedKeys = queryForm.value.principalId
          dialogParam.value.dataType = 'person'
        }
      },
      {
        prop: 'customer',
        placeholder: '请选择客户名称',
        type: 'input',
        maxlength: 50,
        span: 4
        // suffixIcon: 'el-icon-search',
        // click: ({ value, column }) => {
        //   //客户名称选择
        //   dialogParamA.value.tabVal = queryForm.value.cusType || 'customer'
        //   dialogParamA.value.type = 'customer'
        //   dialogParamA.value.title = '选择客户名称'
        //   dialogParamA.value.isDialog = true
        //   dialogParamA.value.multiple = false
        //   dialogParamA.value.nodeKey = 'id'
        //   dialogParamA.value.defaultCheckedKeys = [queryForm.value.cusId]
        //   dialogParamA.value.defaultCheckedLabel = queryForm.value.customer
        // },
        // change: ({ value, column }) => {
        //   if (!value) {
        //     queryForm.value.customer = ''
        //     queryForm.value.cusType = ''
        //     queryForm.value.cusId = ''
        //   }
        // }
      }
      // {
      //   prop: 'cusId',
      //   type: 'select',
      //   multiple: true,
      //   remote: true,
      //   placeholder: '请选择客户名称',
      //   span: 3
      //   // dicUrl: `${baseUrl}/getProvince?id={{key}}`,
      // }
    ]
  },
  // 操作按钮操作
  singleBtn: true,
  multipleBtn: true,
  // table 总数据
  tableTotal: 0,
  //选中的id
  tableSelectIds: [],
  //table 数据
  tableData: [],
  /** 高级搜索 */
  // 查询条件form表单配置
  searchFormOption: {
    labelWidth: 120,
    submitBtn: false,
    emptyBtn: false,
    column: [
      {
        prop: 'proName',
        label: '项目名称',
        placeholder: '请输入项目编号或项目名称',
        maxlength: 50,
        type: 'input'
      },
      {
        prop: 'busType',
        label: '业务属性',
        placeholder: '请选择业务属性',
        type: 'select',
        dicData: business_attribute
      },
      {
        label: '项目属性',
        prop: 'proType',
        placeholder: '请选择项目属性',
        type: 'select',
        dicData: project_properties
      },
      {
        prop: 'customer',
        label: '客户名称',
        placeholder: '请选择客户名称',
        type: 'input',
        suffixIcon: 'el-icon-search',
        click: ({ value, column }) => {
          //客户名称选择
          dialogParamA.value.tabVal = queryForm.value.cusType || 'customer'
          dialogParamA.value.type = 'customer'
          dialogParamA.value.title = '选择客户名称'
          dialogParamA.value.isDialog = true
          dialogParamA.value.multiple = false
          dialogParamA.value.nodeKey = 'id'
          dialogParamA.value.defaultCheckedKeys = [queryForm.value.cusId]
          dialogParamA.value.defaultCheckedLabel = queryForm.value.customer
        },
        change: ({ value, column }) => {
          if (!value) {
            queryForm.value.customer = ''
            queryForm.value.cusType = ''
            queryForm.value.cusId = ''
          }
        }
      },
      // {
      //   label: '客户名称',
      //   prop: 'cusId',
      //   type: 'select',
      //   placeholder: '请选择客户名称'
      // },
      {
        label: '归属单位',
        prop: 'companyIds',
        placeholder: '请选择归属单位',
        type: 'tree',
        multiple: true,
        props: {
          value: 'id'
        },
        dicData: companyOption
      },
      {
        prop: 'principalId',
        label: '项目负责人',
        placeholder: '请选择项目负责人',
        type: 'select',
        clearable: false,
        props: {
          value: 'uuid'
        },
        dicData: principalIdsOption,
        multiple: true,
        click: ({ value, column }) => {
          dialogParam.value.type = 'principalId'
          dialogParam.value.title = '请选择项目负责人'
          dialogParam.value.isDialog = true
          dialogParam.value.multiple = true
          dialogParam.value.nodeKey = 'uuid'
          dialogParam.value.defaultCheckedKeys = queryForm.value.principalId
          dialogParam.value.dataType = 'person'
        }
      },
      {
        prop: 'biddingResult',
        placeholder: '请选择投标结果',
        label: '投标结果',
        type: 'select',
        dicData: [
          {
            label: '中标',
            value: 1
          },
          {
            label: '未中标',
            value: 0
          }
        ]
      },
      {
        label: '投标时间',
        type: 'daterange',
        prop: 'bidOpeningTime',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间'
      },
      {
        label: '项目金额',
        prop: 'proSum',
        placeholder: '请选择项目金额',
        type: 'select',
        dicData: project_amount
      }
    ]
  }
})
const {
  dialogParam,
  advancedSearchParam,
  tableLoading,
  queryForm,
  queryFormOption,
  singleBtn,
  multipleBtn,
  tableData,
  tableSelectIds,
  tableTotal,
  searchFormOption
} = toRefs(data)
//查询按钮操作
const handleSubmit = () => {
  advancedSearchParam.value.drawerVisible = false
  queryForm.value.pageNum = 1
  getList()
}
// 重置按钮操作
const handleEmpty = () => {
  queryForm.value.busType = null
  queryForm.value.proSchedule = null
  queryForm.value.proType = null
  queryForm.value.principalId = null //项目负责人id 前端用
  queryForm.value.deptId = null
  queryForm.value.biddingResult = null //投标结果
  queryForm.value.proSum = null //项目金额
  queryForm.value.bidOpeningEndTime = null
  queryForm.value.bidOpeningStartTime = null
  queryForm.value.bidOpeningTime = null //投标时间
  queryForm.value.cusId = null
  queryForm.value.proName = null
  queryForm.value.companyIds = null
  queryForm.value.cusType = null
  queryForm.value.customer = null
  getList()
}
// 高级筛选 打开弹出框
const openDrawer = () => {
  advancedSearchParam.value.drawerVisible = true
}
// 关闭弹出框高级筛选
const closeAdvancedSearchFn = val => {
  advancedSearchParam.value.drawerVisible = false
}
const closeFn = val => {
  dialogParam.value.isDialog = false
}
// 新建项目
const handleAdd = () => {
  const roleIds = tableSelectIds.value
  router.push({
    path: '/sales/projectManage/addProject'
  })
}
// 编辑项目
const handleEdit = () => {
  const roleIds = tableSelectIds.value
  router.push({
    path: '/sales/projectManage/editProject',
    query: { id: roleIds.toString() }
  })
}
const delTips = idArr => {
  if (!idArr) {
    return false
  }
  const list = JSON.parse(JSON.stringify(tableData.value))
  const result = list.filter(item => {
    return (
      idArr.includes(item.projectId) &&
      (item.createBy !== userStore.name || item.bpmnStatusId !== '00')
    )
  })
  return result
}
// 删除项目
const handleDel = () => {
  const roleIds = tableSelectIds.value
  const result = delTips(roleIds)
  if (result && result.length > 0) {
    const createByArray = result.map(item => item.proName)
    const name = createByArray.join(',')
    proxy.$modal.msgError('没有操作 "' + name + '" 项目的权限')
    return false
  }
  proxy.$modal
    .confirm('是否确认删除该的数据项?')
    .then(function () {
      return delProRemoveById(toRaw(roleIds))
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
// table选中事件
const handleTableSelect = val => {
  tableSelectIds.value = val.map(item => item.projectId)
  singleBtn.value = val.length != 1
  multipleBtn.value = !val.length
}
//查询table列表
function getList() {
  tableLoading.value = true
  let param = { ...queryForm.value }
  // 获取项目id
  param.principalIds = queryForm.value.principalId
    ? getPricipalId(principalIdsOption.value, queryForm.value.principalId)
    : null
  param.bidOpeningStartTime = queryForm.value.bidOpeningTime
    ? queryForm.value.bidOpeningTime[0]
    : ''
  param.bidOpeningEndTime = queryForm.value.bidOpeningTime
    ? queryForm.value.bidOpeningTime[1]
    : ''
  delete param.bidOpeningTime
  getOrdproject(param).then(res => {
    tableLoading.value = false
    tableData.value = res.rows
    tableTotal.value = res.total
  })
}
// 项目名称点击
const handleClickProject = row => {
  router.push({
    path: '/sales/projectManage/projectDetails',
    query: { id: row.projectId }
  })
}
/** 弹出框下拉框
 * 项目负责人，客户名称，归属单位
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  console.log(val, '----val')
  switch (val.type) {
    case 'principalId':
      principalIdsOption.value = val.selectData
      queryForm.value.principalId = val.defaultCheckedKeys
      break
    case 'customer':
      // 客户名称
      console.log(queryForm.value.customer, val, 'val--')
      queryForm.value.cusType = val.tabVal
      queryForm.value.customer = val.labelData ? val.labelData.toString() : null
      queryForm.value.cusId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
  }
}
getList()
</script>
<style lang="scss">
.projectList .avue-form__menu.avue-form__menu--center {
  text-align: left !important;
}
// .projectList .avue-form__group .avue-form__row {
//   margin-left: 10px;
// }
</style>
